<template>
  <div class="demo-container">
    <div class="titleTips">
      <h2>表格组件综合功能演示</h2>
    </div>

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <AdvancedTable
        ref="tableRef"
        :data="tableData"
        :columns="currentColumns"
        :selection="tableConfig.selection"
        :show-index="tableConfig.showIndex"
        :row-draggable="tableConfig.rowDraggable"
        :on-row-drop="handleRowDrop"
        :page-limit="1000"
        :page-size="100"
        :current-page="currentPage"
        height="500px"
        @selection-change="handleSelectionChange"
        @page-change="handlePageChange"
      >
        <!-- 自定义头部工具栏 -->
        <template #toolbar>
          <div class="toolbar">
            <!-- 新增删除 -->
            <div class="control-items">
              <el-button-group size="small">
                <el-button type="primary" :icon="Plus">新增</el-button>
                <el-button
                  type="danger"
                  :icon="Delete"
                  :disabled="selectedRows.length === 0"
                  >删除</el-button
                >
              </el-button-group>
            </div>
            <!-- 多级表头  合并单元格-->
            <div class="control-items">
              <el-radio-group v-model="tableConfig.headerType" size="small">
                <el-radio-button label="normal">普通表头</el-radio-button>
                <el-radio-button label="multi">多级表头</el-radio-button>
              </el-radio-group>
              <el-radio-group v-model="tableConfig.mergeType" size="small">
                <el-radio-button label="none" @click="loadMergeNullData"
                  >不合并</el-radio-button
                >
                <el-radio-button label="row" @click="loadMergeTestData"
                  >行合并</el-radio-button
                >
                <el-radio-button label="column" @click="loadColumnMergeTestData"
                  >列合并</el-radio-button
                >
                <el-radio-button label="both" @click="loadBothMergeTestData"
                  >行列合并</el-radio-button
                >
              </el-radio-group>
            </div>

            <!-- 单选多选 显示隐藏序号 -->
            <div class="control-items">
              <el-switch
                v-model="tableConfig.selection"
                active-text="多选"
                inactive-text="单选"
              />
              <el-switch
                v-model="tableConfig.showIndex"
                active-text="显示序号"
                inactive-text="隐藏序号"
              />
              <el-switch
                v-model="tableConfig.rowDraggable"
                active-text="启用拖拽"
                inactive-text="禁用拖拽"
              />
            </div>
            <!-- 导入导出数据 -->
            <div class="control-items">
              <ExcelImporter
                :column-map="columnMap"
                :validation-rules="validationRules"
                @import-success="handleImportSuccess"
                @import-error="handleImportError"
                @validation-error="handleValidationError"
              >
                <template #trigger>
                  <div class="control-items">
                    <el-button type="primary" :icon="Upload"
                      >导入Excel数据</el-button
                    >
                    <el-button
                      type="success"
                      :icon="Download"
                      @click.stop="exportToExcel"
                      :disabled="tableData.length === 0"
                      >导出Excel数据</el-button
                    >
                  </div>
                </template>
              </ExcelImporter>
            </div>
          </div>
          <!-- 生成多条数据 -->
          <div class="toolbar">
            <div class="control-items">
              <el-button type="warning" @click="generateLargeData(10000)"
                >生成10000条数据</el-button
              >
              <el-button type="danger" @click="clearData">清空数据</el-button>
              <span v-if="tableData.length > 0" class="data-info">
                <p>
                  当前数据量: <strong>{{ tableData.length }}</strong> 条
                </p>
              </span>
            </div>
          </div>
          <div v-if="loading" class="loading-info">生成数据中，请稍候...</div>
        </template>

        <!-- 自定义列 -->
        <template #operation="{ row }">
          <el-button type="primary" link size="small" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button type="danger" link size="small" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </AdvancedTable>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { Upload, Delete, Plus, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { AdvancedTable, ExcelImporter } from '../components/Table'
import * as XLSX from 'xlsx'
import {
  finalRowMerge,
  finalColMerge,
  finalBothMerge,
  generateMockData,
  generateMergeTestData,
  generateColumnMergeTestData,
  validationRules as defaultRules,
} from '../components/Table/utils'

// 表格引用
const tableRef = ref()

// 表格配置
const tableConfig = reactive({
  selection: true,
  showIndex: true,
  headerType: 'normal', // 'normal' 或 'multi'
  mergeType: 'none', // 'none', 'row', 'column', 'both'
  rowDraggable: false,
})

// 分页相关
const currentPage = ref(1)

// 数据相关
const tableData = ref<any[]>([])
const loading = ref(false)
const selectedRows = ref<any[]>([])

// 拖拽日志
const dropLogs = ref<string[]>([])

// Excel导入相关
const columnMap = {
  姓名: 'name',
  年龄: 'age',
  电话: 'phone',
  邮箱: 'email',
  地址: 'address',
  部门: 'department',
  职位: 'position',
}

// 验证规则
const validationRules = {
  name: defaultRules.name,
  age: defaultRules.age,
  phone: defaultRules.phone,
  email: defaultRules.email,
}

const validationErrors = ref<any[]>([])
const importedData = ref<any[]>([])

// 普通表头列定义
const normalColumns = [
  {
    prop: 'name',
    label: '姓名',
    width: 120,
    sortable: true,
  },
  {
    prop: 'age',
    label: '年龄',
    width: 80,
    sortable: true,
  },
  {
    prop: 'department',
    label: '部门',
    width: 120,
  },
  {
    prop: 'position',
    label: '职位',
    width: 120,
  },
  {
    prop: 'phone',
    label: '电话',
    width: 130,
  },
  {
    prop: 'email',
    label: '邮箱',
    width: 200,
  },
  {
    prop: 'address',
    label: '地址',
    minWidth: 180,
  },
  {
    prop: 'operation',
    label: '操作',
    width: 120,
    fixed: 'right',
  },
]

// 多级表头列定义
const multiLevelColumns = [
  {
    prop: 'name',
    label: '姓名',
    width: 120,
  },
  {
    label: '个人信息',
    children: [
      {
        prop: 'age',
        label: '年龄',
        width: 80,
      },
      {
        label: '联系方式',
        children: [
          {
            prop: 'phone',
            label: '电话',
            width: 130,
          },
          {
            prop: 'email',
            label: '邮箱',
            width: 200,
          },
        ],
      },
    ],
  },
  {
    label: '工作信息',
    children: [
      {
        prop: 'department',
        label: '部门',
        width: 120,
      },
      {
        prop: 'position',
        label: '职位',
        width: 120,
      },
    ],
  },
  {
    prop: 'address',
    label: '地址',
    minWidth: 180,
  },
  {
    prop: 'operation',
    label: '操作',
    width: 120,
    fixed: 'right',
  },
]

// 当前使用的列定义
const currentColumns = computed(() => {
  return tableConfig.headerType === 'multi' ? multiLevelColumns : normalColumns
})

// 生成大量数据
const generateLargeData = async (count: number) => {
  loading.value = true

  try {
    // 使用setTimeout模拟异步生成大量数据，避免阻塞UI
    await new Promise<void>((resolve) => {
      setTimeout(() => {
        tableData.value = generateMockData(count)
        resolve()
      }, 300)
    })

    currentPage.value = 1
    ElMessage.success(`成功生成 ${count} 条测试数据`)
  } catch (error) {
    ElMessage.error('生成数据失败')
  } finally {
    loading.value = false
  }
}
// 不合并测试数据
const loadMergeNullData = () => {
  tableData.value = generateMergeTestData()
  currentPage.value = 1
  tableConfig.mergeType = 'none'
  nextTick(() => {
    if (tableRef.value) {
      const table = tableRef.value.$refs.elTable
    }
  })
  ElMessage.success('已加载行合并测试数据，并自动选择"不合并"模式')
}
// 加载合并测试数据
const loadMergeTestData = () => {
  tableData.value = generateMergeTestData()
  currentPage.value = 1
  tableConfig.mergeType = 'row'
  // 为表格列设置数据源，用于合并计算
  nextTick(() => {
    if (tableRef.value) {
      const table = tableRef.value.$refs.elTable
      if (table) {
        const columns = table.columns || []
        columns.forEach((col: any) => {
          if (col) {
            col._children = tableData.value
            col.__tableData = tableData.value
          }
        })
      }
    }
  })
  ElMessage.success('已加载行合并测试数据，并自动选择"行合并"模式')
}

// 加载列合并测试数据
const loadColumnMergeTestData = () => {
  tableData.value = generateColumnMergeTestData()
  currentPage.value = 1
  tableConfig.mergeType = 'column'
  // 为表格列设置数据源，用于合并计算
  nextTick(() => {
    if (tableRef.value) {
      const table = tableRef.value.$refs.elTable
      if (table) {
        const columns = table.columns || []
        columns.forEach((col: any) => {
          if (col) {
            col._children = tableData.value
            col.__tableData = tableData.value
          }
        })
      }
    }
  })
  ElMessage.success('已加载列合并测试数据，并自动选择"列合并"模式')
}

// 加载行列同时合并测试数据
const loadBothMergeTestData = () => {
  tableData.value = generateMergeTestData()
  currentPage.value = 1
  tableConfig.mergeType = 'both'
  // 为表格列设置数据源，用于合并计算
  nextTick(() => {
    if (tableRef.value) {
      const table = tableRef.value.$refs.elTable
      if (table) {
        const columns = table.columns || []
        columns.forEach((col: any) => {
          if (col) {
            col._children = tableData.value
            col.__tableData = tableData.value
          }
        })
      }
    }
  })
  ElMessage.success('已加载行列同时合并测试数据，并自动选择"行列合并"模式')
}

// 清空数据
const clearData = () => {
  tableData.value = []
  currentPage.value = 1
  ElMessage.info('数据已清空')
}

// 清空拖拽日志
const clearLogs = () => {
  dropLogs.value = []
}

// 处理行拖拽
const handleRowDrop = (oldIndex: number, newIndex: number) => {
  // 记录拖拽日志
  const item = tableData.value[oldIndex]
  dropLogs.value.unshift(
    `${new Date().toLocaleTimeString()} - 将 "${item.name}" 从位置 ${
      oldIndex + 1
    } 移动到 ${newIndex + 1}`
  )

  // 将日志限制为最新的15条
  if (dropLogs.value.length > 15) {
    dropLogs.value = dropLogs.value.slice(0, 15)
  }

  // 更新数据顺序
  const draggedItem = tableData.value.splice(oldIndex, 1)[0]
  tableData.value.splice(newIndex, 0, draggedItem)

  ElMessage.success(`记录 "${item.name}" 已移动`)
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
}

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 处理导入成功
const handleImportSuccess = (data: any[]) => {
  tableData.value = data
  importedData.value = data
  validationErrors.value = []
  ElMessage.success(`成功导入 ${data.length} 条数据`)
}

// 处理导入错误
const handleImportError = (error: any) => {
  ElMessage.error(`导入失败: ${error.message || '未知错误'}`)
}

// 处理验证错误
const handleValidationError = (errors: any[]) => {
  validationErrors.value = errors
  ElMessage.error(`数据验证失败，共有 ${errors.length} 处错误`)
}

// Excel数据导出
const exportToExcel = () => {
  // 创建工作簿
  const workbook = XLSX.utils.book_new()

  // 准备导出数据
  const exportData = tableData.value.map((item) => {
    // 反向映射列名(英文->中文)
    const result: Record<string, any> = {}
    const reverseColumnMap: Record<string, string> = {}

    // 创建反向映射
    Object.keys(columnMap).forEach((key) => {
      reverseColumnMap[columnMap[key]] = key
    })

    // 使用反向映射将字段名转为中文
    Object.keys(item).forEach((key) => {
      if (reverseColumnMap[key]) {
        result[reverseColumnMap[key]] = item[key]
      } else {
        result[key] = item[key]
      }
    })

    return result
  })

  // 创建工作表
  const worksheet = XLSX.utils.json_to_sheet(exportData)
  XLSX.utils.book_append_sheet(workbook, worksheet, '数据表')

  // 导出文件
  XLSX.writeFile(workbook, `表格数据_${new Date().toLocaleDateString()}.xlsx`)
  ElMessage.success('数据导出成功')
}

// 操作按钮事件
const handleEdit = (row: any) => {
  ElMessage.info(`编辑记录: ${row.name}`)
}

const handleDelete = (row: any) => {
  ElMessage.warning(`删除记录: ${row.name}`)
}

// 初始化一些示例数据
generateLargeData(50)
</script>

<style scoped>
.demo-container {
  padding: 20px;
}

h2 {
  margin-top: 0;
  margin-bottom: 10px;
}

h3 {
  margin: 0;
  font-size: 18px;
}

h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
}
.titleTips {
  color: #409eff;
  text-align: center;
  margin-bottom: 30px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.control-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.control-group {
  width: 48%;
}

.control-items {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.selected-info {
  color: #409eff;
  font-weight: bold;
}

.loading-info {
  margin: 10px 0;
  color: #409eff;
  font-weight: bold;
}

.data-info {
  margin-top: 10px;
}

.log-item {
  padding: 5px 0;
  border-bottom: 1px dashed #ebeef5;
  font-size: 12px;
}

.table-wrapper {
  margin-top: 20px;
}

.button-group {
  display: flex;
  gap: 10px;
}
</style>
